import tkinter as tk
from tkinter import ttk
import os
import windnd
from threading import Thread
import shutil
from ctypes import windll
from PIL import Image, ImageTk
import win32con,win32security,win32api
# import psutil
# import ntsecuritycon

# 提那家任务栏图标
def add_taskbar_icon(root, icon):
    # 获取窗口句柄
    hwnd = windll.user32.GetParent(root.winfo_id())
    if hwnd != 0:
        large_icon = Image.open(icon)
        large_icon.thumbnail((256, 256), Image.ANTIALIAS)
        large_icon_hdc = large_icon.hdc

        small_icon = Image.open(icon)
        small_icon.thumbnail((16, 16), Image.ANTIALIAS)
        small_icon_hdc = small_icon.hdc

        windll.shell32.SetTaskbarItemIcon(hwnd, large_icon_hdc, small_icon_hdc)




root = tk.Tk()
root.title("Excel图片提取--出品人:Creedassin")

# 在任务栏添加图标
add_taskbar_icon(root, 'ExcelPictures21.ico')  # 替换为你的图标文件路径
root.geometry("612x488")
root.resizable(False, False)
root.iconbitmap("ExcelPictures21.ico")
# 自定义字体
font_style = "楷体"

var = tk.StringVar()
options = ['选项1', '选项2', '选项3']
new_options = ['新选项1', '新选项2', '新选项3']  # 新选项列表


# 创建并布局label_warning、label_volume、text、btn_execute等组件

label_warning = tk.Label(root, text="注意：请在粉碎文件之前关闭相关的文件或程序，否则可能会出现错误。", foreground="red",font=(font_style, 12, "bold"))
label_warning.pack()

label_volume = tk.Label(root, text="文件数量：0\t文件夹数量：0\t总数据：0\n删除成功：0\t异常文件：0", font=(font_style, 12))
label_volume.pack(pady=10)

text = tk.Text(root, width=84, height=6, font=(font_style, 12), bg="#EFEFEF")
text.pack(padx=10, pady=10)
text.insert("insert", "将要提取的Excel文件或者文件夹拖拽到此处！")
text.configure(state="disabled")

# textpicture_id = tk.Text(root,width=84,height=6, font=(font_style, 12), bg="#EFEFEF")
# textpicture_id.pack(padx=10, pady=10)
# textpicture_id.insert("insert", "选择你要使用字段")


f1=tk.Frame(root)
f1.pack(side=tk.TOP,padx=30,pady=20,fill=tk.X,anchor="center")


label_ziduan = tk.Label(f1,width=15,font=(font_style, 12), bg="#EFEFEF",text='图片命名字段：')
label_ziduan.pack(side=tk.LEFT,pady=15,anchor=tk.E)
combobox = ttk.Combobox(f1,width=20,height=10, textvariable=var, values=options,font=(font_style, 12))
combobox.pack(side=tk.LEFT,padx=2,pady=5,anchor="w")

# 更新下拉选项
def update_options():
    combobox['values'] = new_options  # 更新选项列表
    combobox.set('选择新选项')  # 可选，重置选中项或保持不变

update_button = ttk.Button(f1, text="更新选项",width=20, command=update_options)
update_button.pack(side=tk.LEFT,padx=5,pady=5)



files_A = []
folder_A = []
folder_B = []
G = []
errnum=0
def change_oweruser(folder_path):
    global G
    try:
        try:
            path = os.path.dirname(folder_path)
        except:
            path=folder_path
        username = win32api.GetUserName()
        # username='inspur'
        domain = win32api.GetComputerName()
        sid = win32security.LookupAccountName(domain, username)[0]
        # 使用函数
        # change_owner2(folder_path)
        # print(sid,'\n',username)
        # 获取当前文件夹的安全描述符
        sd = win32security.GetFileSecurity(path, win32security.DACL_SECURITY_INFORMATION)
        # 创建一个空的安全描述符
        # sd = PySECURITY_DESCRIPTOR()
        # print(sd)
        # 获取新所有者的SID
        # new_owner_sid = win32security.LookupAccountName("", new_owner)[0]

        # 修改所有者
        sd.SetSecurityDescriptorOwner(sid, False)

        # 应用安全描述符
        win32security.SetFileSecurity(folder_path, win32security.DACL_SECURITY_INFORMATION,sd )
        # print(f"所有者已成功更改为 {username} 目录: {folder_path}")
    except Exception as e:
        G.append("修改文件所有者失败！\n"+"建议：手动打开文件或文件夹属性卡，点击安全标签卡，编辑修改或者高级选项，修改人员信息。")
        print(f"修改所有者失败: {e}")


def handle_drag(files):
    # print(files)
    global files_A, folder_A, folder_B, G
    files_A = []
    folder_A = []
    folder_B = []
    G = []

    text.configure(state="normal")
    text.delete("1.0", "end")
    for file in files:
        file = file.decode("gbk")
        change_oweruser(file)



        if os.path.isfile(file) : #and (file.split('.')[-1] in list_out)
            text.insert("insert", file.replace("\\", "/") + "\n")
            files_A.append(file.replace("\\", "/"))
        else:
            folder_A.append(file)

    for folder in folder_A:
        for a in os.walk(folder.replace("\\", "/")):
            folder_B = [a[0].replace("\\", "/")] + folder_B # 与文件夹列表B拼接
            for file in a[2]: # 获取目录下的文件
                text.insert("insert", os.path.join(a[0], file).replace("\\", "/") + "\n")
                files_A.append(os.path.join(a[0], file).replace("\\", "/"))

    for folder in folder_B:
        text.insert("insert", folder + "\n")

    label_volume.config(
        text=f"文件数量：{len(files_A)}\t文件夹数量：{len(folder_B)}\t总数据：{len(files_A) + len(folder_B)}\n执行成功：0\t异常文件：0")
    text.configure(state="disabled")


# 删除文件
def delete_file(file):
    """
        修改文件属性
        :param file_path: 文件路径
        :param attribute: 要修改的属性
        :param set_or_clear: 设置(True)或清除(False)属性
        """
    global G,errnum
    if os.path.isfile(file):
        try:
            win32api.SetFileAttributes(file, win32con.FILE_ATTRIBUTE_NORMAL)

            list_out = ['zip', '7z', 'rar', 'gz', 'tar', 'bz2', 'xz', 'wim']
            if file.split('.')[-1] not in list_out:
                for i in range(1,10):
                    with open(file, "w") as f:
                        f.write(f"{i}得打akuhfiauwfhauifgiauwfgaiufgauiwfgufwagfuugfaguuggufgaufuggufgufwgufgfgufgufgfgwfuggfgufwug完")
                    f.close()
            os.remove(file)
            text.configure(state="normal")
            text.insert("insert", "· 处理完成 >>" + file + "\n")
            text.see(tk.END)
            text.configure(state="disabled")
        except:
            try:
                os.unlink(file)
            except Exception as e:
                errnum=errnum+1
                err="【异常文件未处理】 >>" + file+'\n'+str(e)
                G.append(err)
    else:
        errnum=errnum+1
        G.append("【异常文件未处理】 >>未找到文件" + file)


# 处理文件夹
def delete_folder(folder):
    global G,errnum
    if os.path.isfile(folder) == False:
        if os.path.exists(folder):
            try:
                command = f'attrib -R "{folder}" /S /D'
                os.system(command)
                shutil.rmtree(folder)
                text.configure(state="normal")
                text.insert("insert", "· 处理完成 >>" + folder + "\n")
                text.see(tk.END)
                text.configure(state="disabled")
            except:
                errnum=errnum+1
                G.append("【异常文件夹未处理】 >>文件夹处理失败：" + folder)
        else:
            errnum=errnum+1
            G.append("【异常文件夹未处理】 >>" + folder)
    else:
        errnum=errnum+1
        G.append("【异常文件夹未处理】 >>" + folder)


def execute():
    def task():
        global folder_B,errnum
        if btn_execute["state"] == "disabled":
            return
        else:
            text.configure(state="normal")
            text.delete("1.0", "end")
            text.configure(state="disabled")
            btn_execute["state"] = "disabled"
            for file in files_A:
                delete_file(file)

            for folder in folder_B:
                delete_folder(folder)

            for item in G:
                text.configure(state="normal")
                text.insert("insert", f"{item}\n")
                text.see(tk.END)
                text.configure(state="disabled")
            seccess=len(files_A) + len(folder_B) - errnum
            if seccess<0:
                seccess=0
            label_volume.config(
                text=f"文件数量：{len(files_A)}\t文件夹数量：{len(folder_B)}\t总数据：{len(files_A) + len(folder_B)}\n执行成功：{seccess}\t异常文件：{errnum}")
            btn_execute["state"] = "normal"

    Thread(target=task).start()


btn_execute = tk.Button(root, text="一键粉碎", width=20, command=execute, font=(font_style, 12), foreground="#FFFFFF",
                        background="#0055FF")
btn_execute.pack(pady=10)

windnd.hook_dropfiles(root, func=handle_drag)

# 自定义按钮样式
style = ttk.Style()
style.configure("Custom.TButton", font=(font_style, 12), foreground="#FFFFFF", background="#0055FF", padding=8)

root.mainloop()